﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BaseEpub
{
    /// <summary>
    /// 南京大学出版社的OPF解析
    /// </summary>
    public class NdPressOpf:IOpfBase
    {
        public EbookInfo GetEbookInfo(string opfPath)
        {
            XDocument xd = XDocument.Load(opfPath);
            XElement root = xd.Root;
            XElement metadata = root.Elements().Where(m => m.Name.LocalName == "metadata").First();
            EbookInfo eInfo = new EbookInfo();
            #region 南大社的计算
            foreach (XElement item in metadata.Elements())
            {
                if (item.Attribute("name") != null && item.Attribute("name").Value == "cover")
                {
                    string cover = item.Attribute("content").Value;
                    XElement manifest = root.Elements().Where(m => m.Name.LocalName == "manifest").First();
                    XElement coverEle = manifest.Elements().Where(m => m.Attribute("id").Value == cover).FirstOrDefault();
                    if (coverEle != null)
                    {
                        string coverPathVal = coverEle.Attribute("href").Value;
                        string[] coverPathStr = coverPathVal.Split('/');
                        string coverPath = @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3\OEBPS\" + coverPathStr[0] + @"\" + coverPathStr[1];
                        GetImageTool imgTool = new GetImageTool();
                        Int64 coverId = imgTool.GetImgId(coverPath);
                        eInfo.Cover = coverId;
                    }
                }
                if (item.Attribute("id") != null && item.Attribute("id").Value == "t1")
                {
                    string name = item.Value;
                    eInfo.Name = name;
                }
                if (item.Attribute("id") != null && item.Attribute("id").Value == "create1")
                {
                    string author = item.Value;
                    eInfo.Author = author;
                }
                if (item.Value.Contains("ISBN"))
                {
                    string isbn = item.Value;
                    string result = "";
                    int rNum = 0;
                    //提取数字
                    foreach (var num in isbn)
                    {
                        if (int.TryParse("" + num + "", out rNum))
                        {
                            result += num;
                        }
                    }
                    eInfo.Isbn = result;
                }
            } 
            #endregion
            return eInfo;
        }
    }
}
